package servlet;

import java.io.IOException;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import bean.Goods;
import bean.User;
import dao.CheckSellNum;
import dao.SelectOneGoods;
import dao.SelectOneUser;

/**
 * Servlet implementation class UpdateServlet
 * 检查是否为当前用户发布的商品，只有自己发布的商品才可以修改
 */
public class UpdateServlet extends HttpServlet {
	private static final long serialVersionUID = 1L;
       
    /**
     * @see HttpServlet#HttpServlet()
     */
    public UpdateServlet() {
        super();
        // TODO Auto-generated constructor stub
    }

	/**
	 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
	 */
	@Override
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		// TODO Auto-generated method stub
		doPost(request, response);
	}

	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
	 */
	@Override
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		// TODO Auto-generated method stub
		HttpSession session = request.getSession();
		String usernumString = (String) session.getAttribute("usernum");//取得session中当前用户的字段
		int goodsId = Integer.parseInt(request.getParameter("id"));//取得通过url传过来的用户id
		Goods goods;
		goods = SelectOneGoods.getOneGoods(goodsId);//通过id查询商品信息
		int userId = goods.getUserId();//取得商品出售者id
		if(CheckSellNum.checkNum(userId, usernumString)){//判断商品出售者和当前用户是否为同一人
			request.setAttribute("goods", goods);//若是同一人，将商品塞入request，传入修改页面
			request.getRequestDispatcher("/view/update.jsp").forward(request,
					response);
			return;
		}
		User user;
		user = SelectOneUser.getOneUser(userId);//如果不是用户出售，则跳回商品展示界面，同时刷新商品信息
		request.setAttribute("user", user);
		request.setAttribute("goods", goods);
		request.getRequestDispatcher("/view/detail.jsp").forward(request,
				response);
		return;
	}

}
